package com.linln.wtp.controller.ticket;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.linln.common.enums.TicketEnum;
import com.linln.common.utils.*;
import com.linln.common.vo.JsonResult;
import com.linln.common.vo.PageResult;
import com.linln.component.wtpshiro.annotation.PassToken;
import com.linln.component.wtpshiro.annotation.UserLoginToken;
import com.linln.modules.rate.service.RateService;
import com.linln.modules.shopsService.domain.Shops;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.ticket.domain.Ticket;
import com.linln.modules.ticket.domain.TicketLog;
import com.linln.modules.ticket.service.TicketLogService;
import com.linln.modules.ticket.service.TicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.user.ticket
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.user.ticket
 * @Description: TODO
 * @date Date : 2020年11月23日 11:07
 */
@RestController("userTicketController")
@RequestMapping("/ticket")
@Slf4j
public class TicketController {
    @Autowired
    private TicketLogService ticketLogService;

    @Autowired
    private TicketService ticketService;

    @Autowired
    private ShopsService shopsService;

    @Autowired
    private RateService rateService;

    //获取所有服务券数量
    @GetMapping("/all")
    @UserLoginToken
    public JsonResult getTicket() {
//        return JsonResult.ok().put("total", ticketService.getAllTicketCount(((User) SecurityUtils.getSubject().getPrincipal()).getId()));
        return JsonResult.ok().put("total", ticketService.getAllTicketCount(SessionUtil.getUserId()));
    }

    //获取未使用的服务券
    @UserLoginToken
    @GetMapping("/notUse")
    public PageResult<Ticket> getNotUseTicket(@RequestParam(required = false, defaultValue = "0", value = "pageNum") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer limit) {
//        return resultPageResult(ticketService.getNotUseTicket(((User) SecurityUtils.getSubject().getPrincipal()).getId(), pageNum, limit));
        return resultPageResult(ticketService.getNotUseTicket(SessionUtil.getUserId(), pageNum, limit));
    }

    //获取已使用的服务券
    @UserLoginToken
    @GetMapping("/used")
    public PageResult<Ticket> getUsedTicket(@RequestParam(required = false, defaultValue = "0", value = "pageNum") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer limit) {
//        return resultPageResult(ticketService.getUsedTicket(((User) SecurityUtils.getSubject().getPrincipal()).getId(), pageNum, limit));
        return resultPageResult(ticketService.getUsedTicket(SessionUtil.getUserId(), pageNum, limit));
    }

    //获取已过期的服务券
    @UserLoginToken
    @GetMapping("/expire")
    public PageResult<Ticket> getExpireTicket(@RequestParam(required = false, defaultValue = "0", value = "pageNum") Integer pageNum, @RequestParam(required = false, defaultValue = "10") Integer limit) {
//        return resultPageResult(ticketService.getExpireTicket(((User) SecurityUtils.getSubject().getPrincipal()).getId(), pageNum, limit));
        return resultPageResult(ticketService.getExpireTicket(SessionUtil.getUserId(), pageNum, limit));
    }


    //生成二维码
    @PassToken
    @GetMapping("/QRCode/{ticketId}")
    public void getTicketInfo(@PathVariable("ticketId") String ticketId, HttpServletResponse response) {
        try {
            byte[] qrCodeImage = QRCodeUtil.getQRCodeImage(ticketId, 200, 200);
            response.getOutputStream().write(qrCodeImage);
        } catch (Exception e) {
            try {
                response.getWriter().print(JsonResult.error("生成二维码失败"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Value("${server.ip}ticket/QRCode/")
    private String QRUrl;

    //服务券详情
    @UserLoginToken
    @GetMapping("/info/{ticketId}")
    public Map<String, Object> ticketInfo(@PathVariable("ticketId") String ticketId) {
        Map<String, Object> map = new HashMap<>();
        Ticket ticketInfo = ticketService.getTicketInfo(ticketId);
        if (TicketEnum.USED.getCode().equals(ticketInfo.getStatus())) {
            TicketLog ticketLog = ticketLogService.getOne(new QueryWrapper<TicketLog>().eq("ticket_id", ticketId));
            Shops shops = shopsService.getById(ticketLog.getShopId());
            Map<String, Object> orderInfo = new HashMap<>();
            //消费时间
            orderInfo.put("consumeDate", DateUtil.formatDate(ticketLog.getVerificationDate()));
            map.put("orderInfo", orderInfo);

            Map<String, Object> shopInfo = new HashMap<>();
            //店铺id
            shopInfo.put("shopId", shops.getShopId());
            //店铺名称
            shopInfo.put("shopName", shops.getShopName());
            //详细地址
            shopInfo.put("shopAddress", shops.getAddress());
            //联系电话
            shopInfo.put("shopPhone", shops.getPhone());

            shopInfo.put("sparePhone", shops.getSparePhone());

            map.put("shopInfo", shopInfo);
        }
        map.put("code", "200");
        map.put("ticketInfo", ticketInfo);
        //二维码地址
        map.put("QRUrl", QRUrl + ticketInfo.getTicketCode());
        //是否已经评价
        map.put("isRate", rateService.isRateByTicketid(ticketId));
        return map;
    }

//    /**
//     * 通过券码核销
//     *
//     * @param ticketCode 券码
//     * @param car        车牌号
//     * @return
//     */
//    @UserLoginToken
//    @PostMapping(value = "/verification/ticketCode")
//    public JsonResult ticketCodeVerification(@RequestParam("ticketCode") String ticketCode, @RequestParam("car") String car, @RequestParam("imgPath") String imgPath) {
//        try {
//            if (!CodeUtil.VerifyCode(CodeUtil.reduction(ticketCode))) {
//                return JsonResult.error("非法券码");
//            }
//        } catch (Exception e) {
//            return JsonResult.error("非法券码");
//        }
//        try {
////            return ticketService.ticketCodeVerification(((User) SecurityUtils.getSubject().getPrincipal()).getId(), ticketCode);
//            return ticketService.ticketCodeVerification(SessionUtil.getUserId(), ticketCode, car, imgPath);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error(e.getMessage());
//            return JsonResult.error("核销失败");
//        }
//    }

    /**
     * 通过券码核销
     *
     * @param ticketCode 券码
     * @param car        车牌号
     * @return
     */
    @UserLoginToken
    @PostMapping(value = "/verification/ticketCode")
    public JsonResult ticketCodeVerification(@RequestParam("shopId") String shopId, @RequestParam("ticketCode") String ticketCode, @RequestParam("car") String car, @RequestParam("imgPath") String imgPath) {
//        try {
//            if (!CodeUtil.VerifyCode(CodeUtil.reduction(ticketCode))) {
//                return JsonResult.error("非法券码");
//            }
//        } catch (Exception e) {
//            return JsonResult.error("非法券码");
//        }
        try {
//            return ticketService.ticketCodeVerification(((User) SecurityUtils.getSubject().getPrincipal()).getId(), ticketCode);
            return ticketService.ticketCodeVerification(SessionUtil.getUserId(), ticketCode, car, imgPath, shopId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return JsonResult.error("核销失败");
        }
    }


    @UserLoginToken
    @PostMapping(value = "/uploadVerificationImg")
    //保存图片
    public Map<String, Object> saveImg(MultipartFile file) {
        return ticketService.saveVerificationImg(file);
    }


    @UserLoginToken
    @PostMapping(value = "uploadVerificationImgByBase64")
    //通过base64字符串 保存图片
    public Map<String, Object> saveImgBase64(String img) {
        return ticketService.saveVerificationImgByBase64(img);
    }

//    @UserLoginToken
//    /**
//     * 通过id核销  扫描二维码
//     *
//     * @param ticketId 服务券id
//     * @return
//     */
//    @PostMapping("/verification/ticketId")
//    public JsonResult QRCodeverification(@RequestParam("ticketId") String ticketId) {
//        try {
////            return ticketService.ticketIdVerification(((User) SecurityUtils.getSubject().getPrincipal()).getId(), ticketId);
//            return ticketService.ticketIdVerification(SessionUtil.getUserId(), ticketId);
//        } catch (Exception e) {
//            return JsonResult.error(e.getMessage());
//        }
//    }


    /**
     * 组装PageResult
     */
    public PageResult<Ticket> resultPageResult(PageInfo<Ticket> pageInfo) {
        PageResult<Ticket> pageResult = new PageResult<>();
        pageResult.setCode(200);
        pageResult.setData(pageInfo.getList());
        pageResult.setCount(pageInfo.getTotal());
        return pageResult;
    }


    //查询核销历史记录
    @UserLoginToken
    @GetMapping("/verificationRecord")
    public Map<String, Object> getVerificationRecord(@RequestParam("shopId") String shopId, @RequestParam(required = false, defaultValue = "0", value = "pageNum") Integer pageNum, @RequestParam(required = false, defaultValue = "20") Integer limit, @RequestParam(value = "date", required = false) String date) {
        Map<String, Object> verificationRecord;
        try {
            verificationRecord = ticketService.getVerificationRecord(SessionUtil.getUserId(), pageNum, limit, date, shopId);

            verificationRecord.put("code", 200);
        } catch (Exception e) {
            verificationRecord = new HashMap<>();
            verificationRecord.put("code", 500);
            verificationRecord.put("msg", "获取核销列表失败");
        }
        return verificationRecord;
    }
}
